const { getUserAddresses, deleteAddress } = require('../../../../services/address/address');
const addressManager = require('../../../../model/address');
const { getUserData } = require('../../../../model/user');

Page({
  data: {
    addresses: [], // 合并后的完整地址列表
    selectedAddressId: null, // 当前选中的地址
    defaultAddressId: null, // 默认地址 ID
  },

  onShow() {
    this.fetchAddresses();
  },
 
  async fetchAddresses() {
    try {  
      const serverAddresses = await getUserAddresses();
      const localAddresses = addressManager.getAllAddresses();
  
      // 合并本地和服务器地址列表
      const mergedAddresses = serverAddresses.map((serverAddress) => {
        const localAddress = localAddresses[serverAddress.id];
        return {
          ...serverAddress,
          isDefault: localAddress?.isDefault || false, // 优先使用本地的 isDefault 信息
        };
      });
  
      this.setData({ 
        addresses: mergedAddresses,
        selectedAddressId: addressManager.getSelectedAddressId() 
      });
    } catch (error) {
      console.error('Failed to fetch addresses:', error);
    }
  },

  // 设置默认地址
  handleSetDefault(e) {
    const { id } = e.detail;

    // 更新本地缓存中当前用户的默认地址
    const updatedAddresses = this.data.addresses.map((address) => {
      const isDefault = address.id === id;
      addressManager.updateAddress(address.id, { isDefault });
      return { ...address, isDefault };
    });

    this.setData({ addresses: updatedAddresses });
  },

  // 选中地址
  handleSelectAddress(e) {
    const { id } = e.detail;

    this.setData({
      selectedAddressId: id,
    });
    // 更新 AddressManager 中的选中地址 ID
    addressManager.setSelectedAddressId(id);
  },

  // 删除地址
  async handleAddressAction(e) {
    const { action, index } = e.detail;
    const address = this.data.addresses[index];

    switch (action) {
      case 'select':
        wx.navigateBack({ success: () => wx.showToast({ title: '地址已选中' }) });
        break;

      case 'delete':
        wx.showModal({
          title: '删除地址',
          content: '确定删除该地址吗？',
          success: async (res) => {
            if (res.confirm) {
              try {
                // 删除服务器和本地缓存中的地址
                await deleteAddress(address.id);
                addressManager.deleteAddress(address.id);

                const addresses = this.data.addresses.filter((_, i) => i !== index);
                this.setData({ addresses });
                wx.showToast({ title: '地址已删除' });
              } catch (error) {
                console.error('Failed to delete address:', error);
                wx.showToast({ title: '删除失败', icon: 'none' });
              }
            }
          },
        });
        break;

      case 'copy':
        wx.setClipboardData({
          data: `${address.addressLine1}, ${address.city}, ${address.state}, ${address.country}`,
          success: () => wx.showToast({ title: '地址已复制' }),
        });
        break;

      case 'modify':
        wx.navigateTo({ url: `/pages/usercenter/address/edit/index?addressId=${address.id}` });
        break;

      case 'set-default':
        // 直接设置默认地址，不再弹框
        this.handleSetDefault({ detail: { id: address.id } });
        break;

      default:
        break;
    }
  },

  // 添加新地址
  addAddress() {
    wx.navigateTo({ url: '/pages/usercenter/address/edit/index' });
  },
});
